<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="用户" prop="userId">
        <el-input
          v-model="selectedUserDisplay"
          placeholder="请选择用户"
          clearable
          readonly
          @clear="handleClearUser"
          class="!w-240px"
        >
          <template #suffix>
            <Icon
              icon="ep:search"
              class="cursor-pointer hover:text-primary"
              @click="openUserDialog"
            />
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="名称" prop="nickname">
        <el-input
          v-model="queryParams.nickname"
          placeholder="请输入名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="手机号" prop="mobile">
        <el-input
          v-model="queryParams.mobile"
          placeholder="请输入手机号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable class="!w-240px">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.MEMBER_USER_TYPE)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['member:blacklist:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['member:blacklist:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
        <el-button
          type="danger"
          plain
          :disabled="isEmpty(checkedIds)"
          @click="handleDeleteBatch"
          v-hasPermi="['member:blacklist:delete']"
        >
          <Icon icon="ep:delete" class="mr-5px" /> 批量删除
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
      row-key="id"
      v-loading="loading"
      :data="list"
      :stripe="true"
      :show-overflow-tooltip="true"
      @selection-change="handleRowCheckboxChange"
    >
      <el-table-column type="selection" width="55" fixed="left" />
      <el-table-column label="主键ID" align="center" prop="id" width="80" fixed="left" />
      <el-table-column label="用户ID" align="center" prop="userId" width="100" />
      <el-table-column label="名称" align="center" prop="nickname" width="120" />
      <el-table-column label="手机号" align="center" prop="mobile" width="130" />
      <el-table-column label="拉黑原因" align="center" prop="blacklistReason" width="150" />
      <el-table-column label="拉黑详情" align="center" prop="blacklistDetail" width="200" />
      <el-table-column
        label="到期时间"
        align="center"
        prop="expireTime"
        :formatter="dateFormatter"
        width="180"
      />
      <el-table-column label="状态" align="center" prop="status" width="100">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.MEMBER_USER_TYPE" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column
        label="解除时间"
        align="center"
        prop="unblockTime"
        :formatter="dateFormatter"
        width="180"
      />
      <el-table-column label="解除原因" align="center" prop="unblockReason" width="150" />
      <el-table-column label="解除操作人" align="center" prop="unblockOperator" width="120" />
      <el-table-column label="操作人" align="center" prop="operator" width="120" />
      <el-table-column label="备注" align="center" prop="remark" width="150" />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180"
      />
      <el-table-column label="操作" align="center" width="200" fixed="right">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['member:blacklist:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="warning"
            @click="handleRelieve(scope.row)"
            v-hasPermi="['member:blacklist:relieve']"
          >
            解除封禁
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['member:blacklist:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <BlacklistForm ref="formRef" @success="getList" />

  <!-- 用户选择弹窗 -->
  <UserSelectDialog ref="userDialogRef" @confirm="handleUserConfirm" />
</template>

<script setup lang="ts">
import { isEmpty } from '@/utils/is'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { BlacklistApi, BlacklistVO } from '@/api/member/blacklist'
import BlacklistForm from './BlacklistForm.vue'
import UserSelectDialog from './UserSelectDialog.vue'
import type { UserVO } from '@/api/member/user'

/** 会员黑名单管理 列表 */
defineOptions({ name: 'Blacklist' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<BlacklistVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  userId: undefined as number | undefined,
  nickname: undefined,
  mobile: undefined,
  status: undefined
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const userDialogRef = ref() // 用户选择弹窗
const selectedUserDisplay = ref('') // 选中的用户显示信息

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await BlacklistApi.getBlacklistPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  selectedUserDisplay.value = '' // 清空用户显示信息
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await BlacklistApi.deleteBlacklist(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 解除封禁操作 */
const handleRelieve = async (row: BlacklistVO) => {
  // 检查是否为封禁状态（status=true或1表示生效中）
  const isBlocked = row.status === true || row.status === 1 || (row.status as any) === '1'

  if (!isBlocked) {
    message.warning('该用户当前不是封禁状态，无需解除封禁')
    return
  }

  try {
    // 解除封禁的二次确认
    await message.confirm('确认要解除该用户的封禁吗？', '解除封禁')
    // 发起解除封禁
    await BlacklistApi.relieve(row.id)
    message.success('解除封禁成功')
    // 刷新列表
    await getList()
  } catch {}
}

/** 批量删除会员黑名单管理 */
const handleDeleteBatch = async () => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 批量删除：逐个调用删除接口
    await Promise.all(checkedIds.value.map((id) => BlacklistApi.deleteBlacklist(id)))
    checkedIds.value = []
    message.success(t('common.delSuccess'))
    await getList()
  } catch {}
}

const checkedIds = ref<number[]>([])
const handleRowCheckboxChange = (records: BlacklistVO[]) => {
  checkedIds.value = records.map((item) => item.id)
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await BlacklistApi.exportBlacklist(queryParams)
    download.excel(data, '会员黑名单管理.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 打开用户选择弹窗 */
const openUserDialog = () => {
  userDialogRef.value?.open()
}

/** 用户选择确认 */
const handleUserConfirm = (user: UserVO) => {
  queryParams.userId = user.id
  selectedUserDisplay.value = `${user.id} - ${user.nickname || user.name || ''} - ${user.mobile || ''}`
}

/** 清空用户选择 */
const handleClearUser = () => {
  queryParams.userId = undefined
  selectedUserDisplay.value = ''
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script>
